const mongoose = require("mongoose");
const adminsModel = mongoose.model("admins");
const { md5, secretKey } = require("../util/salt");
const jwt = require("jsonwebtoken");

module.exports = {
    // 登陆
    login: async ({ adminName, adminPassword }) => {
        const user = await adminsModel.findOne({ adminName, adminPassword: md5(adminPassword) });
        const data = {};
        if (user) {
            data._id = user._id;
            const payload = {
                name: user.adminName
            };
            data.token = jwt.sign(payload, secretKey, {
                expiresIn: 60 * 60 * 24, // 秒
            });
            return data
        }
        return { code: -1 }
    },
    // 注册
    reg: async ({ adminName, adminPassword, date = new Date() }) => {
        let data = await adminsModel.findOne({ adminName });
        data = !data ? await adminsModel.create({ adminName, adminPassword: md5(adminPassword), date: [date] }) : false;
        return data;
    },
    // 获取数据-分页
    get: async ({ page, limit }) => {
        limit = ~~limit;
        const result = {};
        result.total = await adminsModel.countDocuments();
        result.rows = await adminsModel.find().skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec();
        return result;
    },
    // 添加时间
    addDate: async ({ _id, date }) => await adminsModel.updateOne({ _id }, { $push: { loginDate: date } }),
    // 更新
    update: async (conditions, doc) => await adminsModel.updateOne(conditions, doc),
    //根据find条件查询
    search: async (find, { page = 1, limit = 10 } = {}) => await adminsModel.find(find).skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec(),
    // 删除
    del: async ({ _id }) => await adminsModel.deleteOne({ _id })
}